package com.droidexchange.adapter;

import java.util.List;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.droidexchange.R;
import com.droidexchange.main.DeQuestionsItem;
import com.droidexchange.main.QFilter;

public class QuestionsAdapter extends ArrayAdapter<DeQuestionsItem>
{
	Context	context;

	public QuestionsAdapter(Context context, int resourceId)
	{
		super(context, resourceId);
		this.context = context;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent)
	{
		View elem;

		if (convertView == null)
		{
			elem = LayoutInflater.from(context).inflate(R.layout.question_tab, parent, false);
		}
		else
		{
			elem = convertView;
		}

		DeQuestionsItem post = getItem(position);
		return getView(context, elem, post);
	}

	public static View getView(Context context, View elem, DeQuestionsItem post)
	{
		RelativeLayout topLayout = (RelativeLayout) elem.findViewById(R.id.top_layout);
		topLayout.setTag(Integer.toString(post.question.getPostId()));

		TextView txtQuestionTitle = (TextView) elem.findViewById(R.id.title);
		txtQuestionTitle.setText(post.question.getTitle());

		TextView txtVotes = (TextView) elem.findViewById(R.id.votes);
		txtVotes.setText(getInString(post.question.getUpVoteCount() - post.question.getDownVoteCount()));

		TextView txtAnswerCount = (TextView) elem.findViewById(R.id.answer_count);
		txtAnswerCount.setText(getInString(post.question.getAnswerCount()));

		TextView txtViews = (TextView) elem.findViewById(R.id.views);
		txtViews.setText(getInString(post.question.getViewCount()));

		return elem;
	}

	@Override
	public void clear()
	{
		QFilter.getQFilter().clearList();
		super.clear();
	}
	
	private static String getInString(int num)
	{
		String sAnsCount = "";
		if (num > 9999)
			sAnsCount = " " + num / 1000 + "k";
		else
			sAnsCount = " " + num;

		return sAnsCount;
	}

	private void showTags(DeQuestionsItem post, LinearLayout tagsLayout)
	{
		LayoutParams params = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.FILL_PARENT);

		List<String> tags = post.question.getTags();
		params.weight = (100f) / ((float) tags.size());
		for (int i = 0; i < tags.size(); i++)
		{
			TextView txtV = new TextView(context);
			txtV.setText(tags.get(i));
			tagsLayout.addView(txtV, params);
		}
	}
}
